#!/usr/local/bin/python3
# -*- coding: utf-8 -*-

"""
@File    : cross.py
@Author  : different && 道阻且长,行则将至 行而不辍,未来可期
@Time    : 2021/10/18 16:19
@Desc    : 交叉表

"""
import ujson
from flask import render_template, request, jsonify

from apps import cache
from apps.models import get_or_create
from apps.models.cross_group import CrossAttr, CrossAttrGroup
from apps.view import cross_bp
from expand import db, login_required, auth_management
from expand.exp_data.exp_cross_data import CrossData
from expand.exp_data.tools.data_format import attr_format


@cross_bp.route('/cross/<int:pk>')
@cache.cached(timeout=300)
@login_required
def cross_table(pk):
    if request.method == 'GET':
        cross = CrossData(pk)
        level_1, level_2, level_3 = cross.cross_table_title()
        cross_title = cross.text_title()
        cross_data = ujson.dumps(cross.cross_table_data())
        return render_template('cross.html', level_1=level_1, level_2=level_2, level_3=level_3, cross_title=cross_title,
                               cross_data=cross_data, pk=pk)


@cross_bp.route('/cross/group/<pk>', methods=['GET', 'POST'])
@login_required
@auth_management
def cross_group(pk):
    cache.clear()
    # 获取属性
    if request.method == 'GET':
        cross = CrossData(pk)
        attr_group = cross.cross_attr_group()
        return render_template('attributes.html', attr_group=attr_group, pk=pk)
    param = request.get_json()
    # 获取主属性名
    main_attr = param.pop('main_attr')
    for k, v in param.items():
        if k == main_attr:
            is_main_attr = True
        else:
            is_main_attr = False
        try:
            query = get_or_create(db.session, CrossAttr, attr_name=k, table_id=pk, is_main_attr=is_main_attr)
            [db.session.delete(i) for i in query.attr_group]
            db.session.commit()
            db.session.flush()
            for bound in attr_format(v):
                bound['cross_attr_id'] = query.id
                group = CrossAttrGroup(**bound)
                db.session.add(group)
            db.session.commit()
        except Exception as e:
            print(e)
            return jsonify(code=400, msg='Error')
    return jsonify(code=200, msg='Success')
